const WXAPI = require('apifm-wxapi')
const TOOLS = require('../../utils/tools.js')
const AUTH = require('../../utils/auth')
const CONFIG = require('../../config.js')
const APP = getApp()
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk = new QQMapWX({
  key: 'HM3BZ-SML6Z-YRSXS-76WM7-AFVVJ-7DBEO' // 替换为步骤1中申请的Key
});

Page({
  data: {
     tel: wx.getStorageSync("tel") ? wx.getStorageSync("tel") : '400-025-4668',
    qj: wx.getStorageSync("qj") ? wx.getStorageSync("qj") : 'bz',
    zdydh: wx.getStorageSync("zdydh") ? wx.getStorageSync("zdydh") : '',
    zdylogo: wx.getStorageSync("zdylogo") ? wx.getStorageSync("zdylogo") : '',
    dh_tap_index: 2,
    loading: true,        // 加载状态
    shopList: [],         // 店铺列表
    cityName: '',     // 默认城市
    cityId: '', // 需替换为实际城市ID
    curlatitude: '',      // 用户纬度
    curlongitude: '',      // 用户经度

    showPicker: false,       // 弹窗显示状态
    showCityPicker: false,   // 城市选择器显示状态
    provinces: [],           // 省份列表
    cities: [],              // 城市列表
    provinceIndex: [0],      // 省份选择器索引
    cityIndex: [0],          // 城市选择器索引
    selectedProvince: null,  // 选中的省份
    selectedCity: null       // 选中的城市

  },
  onLoad: function (e) {
    // 页面加载时，先获取用户经纬度
    this.getUserLocation();
    // 页面加载时获取所有省份
    this.fetchProvinces();
  },
  detail(e) {
    console.log(e)
    wx.navigateTo({
     url: '/packageYt/ting/detail?id=' + e.currentTarget.dataset.id,
    })
  },
  // 获取所有省份
  fetchProvinces() {
    let temp = [
      {
        "id": "320000000000",
        "name": "江苏省",
        "nameEn": "Jiangsu",
        "pinyin": "jiangsusheng",
        "jianpin": "jss",
        "firstLetter": "j",
        "level": 1
      },
      {
        "id": "310000000000",
        "name": "上海市",
        "nameEn": "Shanghai",
        "pinyin": "shanghaishi",
        "jianpin": "shs",
        "firstLetter": "s",
        "level": 1
      },
      {
        "id": "370000000000",
        "name": "山东省",
        "nameEn": "Shandong",
        "pinyin": "shandongsheng",
        "jianpin": "sds",
        "firstLetter": "s",
        "level": 1
      },
      {
        "id": "110000000000",
        "name": "北京市",
        "nameEn": "Beijing",
        "pinyin": "beijingshi",
        "jianpin": "bjs",
        "firstLetter": "b",
        "level": 1
      },
      {
        "id": "120000000000",
        "name": "天津市",
        "nameEn": "Tianjin",
        "pinyin": "tianjinshi",
        "jianpin": "tjs",
        "firstLetter": "t",
        "level": 1
      },
      {
        "id": "130000000000",
        "name": "河北省",
        "nameEn": "Hebei",
        "pinyin": "hebeisheng",
        "jianpin": "hbs",
        "firstLetter": "h",
        "level": 1
      },
      {
        "id": "140000000000",
        "name": "山西省",
        "nameEn": "Shanxi",
        "pinyin": "shanxisheng",
        "jianpin": "sxs",
        "firstLetter": "s",
        "level": 1
      },
      {
        "id": "710000000000",
        "name": "台湾",
        "nameEn": "TaiWan",
        "pinyin": "taiwan",
        "jianpin": "tw",
        "firstLetter": "t",
        "level": 1
      },
      {
        "id": "810000000000",
        "name": "香港",
        "nameEn": "Hong Kong",
        "pinyin": "xianggang",
        "jianpin": "xg",
        "firstLetter": "x",
        "level": 1
      },
      {
        "id": "820000000000",
        "name": "澳门",
        "nameEn": "Macao",
        "pinyin": "aomen",
        "jianpin": "am",
        "firstLetter": "a",
        "level": 1
      },
      {
        "id": "530000000000",
        "name": "云南省",
        "nameEn": "Yunnan",
        "pinyin": "yunnansheng",
        "jianpin": "yns",
        "firstLetter": "y",
        "level": 1
      },
      {
        "id": "540000000000",
        "name": "西藏自治区",
        "nameEn": "Tibet",
        "pinyin": "xizangzizhiqu",
        "jianpin": "xzzzq",
        "firstLetter": "x",
        "level": 1
      },
      {
        "id": "610000000000",
        "name": "陕西省",
        "nameEn": "Shaanxi",
        "pinyin": "shanxisheng",
        "jianpin": "sxs",
        "firstLetter": "s",
        "level": 1
      },
      {
        "id": "620000000000",
        "name": "甘肃省",
        "nameEn": "Gansu",
        "pinyin": "gansusheng",
        "jianpin": "gss",
        "firstLetter": "g",
        "level": 1
      },
      {
        "id": "630000000000",
        "name": "青海省",
        "nameEn": "Qinghai",
        "pinyin": "qinghaisheng",
        "jianpin": "qhs",
        "firstLetter": "q",
        "level": 1
      },
      {
        "id": "640000000000",
        "name": "宁夏回族自治区",
        "nameEn": "Ningxia",
        "pinyin": "ningxiahuizuzizhiqu",
        "jianpin": "nxhzzzq",
        "firstLetter": "n",
        "level": 1
      },
      {
        "id": "650000000000",
        "name": "新疆维吾尔自治区",
        "nameEn": "Xinjiang",
        "pinyin": "xinjiangweiwuerzizhiqu",
        "jianpin": "xjwwezzq",
        "firstLetter": "x",
        "level": 1
      },
      {
        "id": "510000000000",
        "name": "四川省",
        "nameEn": "Sichuan",
        "pinyin": "sichuansheng",
        "jianpin": "scs",
        "firstLetter": "s",
        "level": 1
      },
      {
        "id": "520000000000",
        "name": "贵州省",
        "nameEn": "Guizhou",
        "pinyin": "guizhousheng",
        "jianpin": "gzs",
        "firstLetter": "g",
        "level": 1
      },
      {
        "id": "430000000000",
        "name": "湖南省",
        "nameEn": "Hunan",
        "pinyin": "hunansheng",
        "jianpin": "hns",
        "firstLetter": "h",
        "level": 1
      },
      {
        "id": "440000000000",
        "name": "广东省",
        "nameEn": "Guangdong",
        "pinyin": "guangdongsheng",
        "jianpin": "gds",
        "firstLetter": "g",
        "level": 1
      },
      {
        "id": "450000000000",
        "name": "广西壮族自治区",
        "nameEn": "Guangxi",
        "pinyin": "guangxizhuangzuzizhiqu",
        "jianpin": "gxzzzzq",
        "firstLetter": "g",
        "level": 1
      },
      {
        "id": "460000000000",
        "name": "海南省",
        "nameEn": "Hainan",
        "pinyin": "hainansheng",
        "jianpin": "hns",
        "firstLetter": "h",
        "level": 1
      },
      {
        "id": "500000000000",
        "name": "重庆市",
        "nameEn": "Chongqing",
        "pinyin": "zhongqingshi",
        "jianpin": "zqs",
        "firstLetter": "z",
        "level": 1
      },
      {
        "id": "410000000000",
        "name": "河南省",
        "nameEn": "Henan",
        "pinyin": "henansheng",
        "jianpin": "hns",
        "firstLetter": "h",
        "level": 1
      },
      {
        "id": "420000000000",
        "name": "湖北省",
        "nameEn": "Hubei",
        "pinyin": "hubeisheng",
        "jianpin": "hbs",
        "firstLetter": "h",
        "level": 1
      },

      {
        "id": "330000000000",
        "name": "浙江省",
        "nameEn": "Zhejiang",
        "pinyin": "zhejiangsheng",
        "jianpin": "zjs",
        "firstLetter": "z",
        "level": 1
      },
      {
        "id": "340000000000",
        "name": "安徽省",
        "nameEn": "Anhui",
        "pinyin": "anhuisheng",
        "jianpin": "ahs",
        "firstLetter": "a",
        "level": 1
      },
      {
        "id": "350000000000",
        "name": "福建省",
        "nameEn": "Fujian",
        "pinyin": "fujiansheng",
        "jianpin": "fjs",
        "firstLetter": "f",
        "level": 1
      },
      {
        "id": "360000000000",
        "name": "江西省",
        "nameEn": "Jiangxi",
        "pinyin": "jiangxisheng",
        "jianpin": "jxs",
        "firstLetter": "j",
        "level": 1
      },
      {
        "id": "150000000000",
        "name": "内蒙古自治区",
        "nameEn": "Inner Mongolia",
        "pinyin": "neimengguzizhiqu",
        "jianpin": "nmgzzq",
        "firstLetter": "n",
        "level": 1
      },
      {
        "id": "210000000000",
        "name": "辽宁省",
        "nameEn": "Liaoning",
        "pinyin": "liaoningsheng",
        "jianpin": "lns",
        "firstLetter": "l",
        "level": 1
      },
      {
        "id": "220000000000",
        "name": "吉林省",
        "nameEn": "Jilin",
        "pinyin": "jilinsheng",
        "jianpin": "jls",
        "firstLetter": "j",
        "level": 1
      },
      {
        "id": "230000000000",
        "name": "黑龙江省",
        "nameEn": "Heilongjiang",
        "pinyin": "heilongjiangsheng",
        "jianpin": "hljs",
        "firstLetter": "h",
        "level": 1
      }
    ]
      ;
    this.setData({ provinces: temp,selectedProvince: temp[0] });
    this.fetchCities(temp[0].id);
    console.log(temp);

    // WXAPI.provinceV2().then(res => {
    //   this.setData({ provinces: res.data });
    // }).catch(err => {
    //   wx.showToast({
    //     title: err,
    //     icon: 'none'
    //   });
    // });
  },
  // 根据省份ID获取城市列表
  fetchCities(pid) {
    WXAPI.nextRegionV2(pid ? pid : this.data.provinces[0].id).then(res => {
      this.setData({
        cities: res.data,
        showCityPicker: true,
        cityIndex: [0], // 重置城市选择器索引
        selectedCity: res.data[0]
      });
    }).catch(err => {
      wx.showToast({
        title: err,
        icon: 'none'
      });
    });
  },

  // 显示城市选择弹窗
  showCityPicker() {
    this.setData({ showPicker: true });
  },

  // 隐藏城市选择弹窗
  hideCityPicker() {
    this.setData({ showPicker: false, showCityPicker: false });
  },

  // 省份选择器值变化
  onProvinceChange(e) {
    const provinceIndex = e.detail.value[0];
    const selectedProvince = this.data.provinces[provinceIndex];
    this.setData({
      provinceIndex: [provinceIndex],
      selectedProvince
    });
    // 获取该省份下的城市列表
    this.fetchCities(selectedProvince.id);
  },

  // 城市选择器值变化
  onCityChange(e) {
    const cityIndex = e.detail.value[0];
    const selectedCity = this.data.cities[cityIndex];
    this.setData({
      cityIndex: [cityIndex],
      selectedCity
    });
  },

  // 确认选择城市
  confirmCity() {
    console.log("选择的城市是：", this.data.selectedProvince, this.data.selectedCity);
    this.setData({
      cityId: this.data.selectedCity.id,
      cityName: this.data.qj=='hz'||this.data.qj=='bz'?this.data.selectedCity.name:this.data.selectedCity.nameEn
    });
    // 调用接口获取店铺列表
    this.fetchShops(1);
    // wx.showToast({
    //   title: `已选中：${this.data.selectedProvince.name}-${this.data.selectedCity.name}`,
    //   icon: 'success'
    // });
    this.hideCityPicker();
    // 此处可将选中的城市信息传递给其他页面或进行后续业务逻辑
  },


  // 获取用户经纬度
  getUserLocation() {
    wx.getLocation({
      type: 'gcj02', // 国测局坐标系（小程序地图默认使用）
      success: (res) => {
        console.log('用户位置:', res);

        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: (addressRes) => {
            // 321003000000000
            // 321000000000
            // 3. 提取城市ID（city_code）addressRes.result.ad_info.adcode数据市"321003" 改成 321000000000
            const cityId = (addressRes.result.ad_info.adcode).substring(0, 5) + '0000000';
            // const cityId =321000000000;
            // 去掉市或者县或者区
            const cityName = (addressRes.result.ad_info.city).replace(/市|县|区/g, '');
            this.setData({ cityId, cityName });
            console.log('当前城市ID：', cityId, addressRes);
            this.setData({
              curlatitude: res.latitude,
              curlongitude: res.longitude
            });
            // 调用接口获取店铺列表
            this.fetchShops();

          },
          fail: (err) => {
            console.error('逆地址解析失败：', err);
            wx.showToast({
              title: '获取城市ID失败',
              icon: 'none'
            });
          }
        });


      },
      fail: (err) => {
        wx.showToast({
          title: this.data.qj == 'hz' || this.data.qj == 'bz' ? "获取位置失败，请检查权限" : " ",
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    });
  },



  // 调用接口获取店铺列表
  fetchShops(e) {
    const { curlatitude, curlongitude, cityId } = this.data;
    let temp = {

      cityId
    }
    if (!e) {
      temp.curlatitude = curlatitude;
      temp.curlongitude = curlongitude;
    }
    WXAPI.fetchShopsV2(temp).then((res) => {
      if (res.code === 0) { // 假设接口成功码为0
        this.setData({
          shopList: res.data.result,
          loading: false
        });
      } else {
        wx.showToast({
          title: this.data.qj == 'hz' || this.data.qj == 'bz' ? "暂无门店" : "No Shops",
          icon: 'none'
        });
        this.setData({ loading: false, shopList: [] });
      }
    }).catch((err) => {
      wx.showToast({
        title: this.data.qj == 'hz' || this.data.qj == 'bz' ? "暂无门店" : "No Shops",
        icon: 'none'
      });
      this.setData({ loading: false, shopList: [] });
    });
  },





  linkPhone(e) {
    const phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone,
    })
  },

  // 导航按钮点击（示例方法，实际需结合地图导航API）
  handleNav(e) {
    const shopId = e.currentTarget.dataset.id;
    // 可根据shopId获取店铺经纬度，调用wx.openLocation打开地图导航
    const shop = this.data.shopList.find(item => item.id === shopId);
    if (shop) {
      wx.openLocation({
        latitude: shop.latitude,
        longitude: shop.longitude,
        name: shop.name,
        address: shop.address
      });
    }
  },

  zdy_top_nav() {
    wx.navigateTo({
      url: '/pages/xl/index',
    })
  },
  dh_tap(e) {
    //console.log(e);
    let temp = e.currentTarget.dataset.id;
    this.setData({
      dh_tap_index: temp
    })
    if (temp == 0) {
      wx.reLaunch({
        url: '/packageYt/index/index',
      })
    }
    if (temp == 1) {
      wx.reLaunch({
        url: '/packageYt/case/index',
      })
    }
    if (temp == 2) {
      wx.reLaunch({
        url: '/packageYt/ting/index',
      })
    }
    if (temp == 3) {
      wx.reLaunch({
        url: '/packageYt/goods/index',
      })
    }
    if (temp == 4) {
      wx.reLaunch({
        url: '/packageYt/my/index',
      })
    }
  },



  onShow: function (e) {
    this.setData({
      qj: wx.getStorageSync("qj") ? wx.getStorageSync("qj") : 'bz'
    })
  },

  async getGoodsList(categoryId, append) {
    if (categoryId == 0) {
      categoryId = "";
    }
    wx.showLoading({
      title: ''
    })
    // https://www.yuque.com/apifm/nu0f75/wg5t98
    const res = await WXAPI.goodsv2({
      categoryId: categoryId,
      page: this.data.curPage,
      pageSize: this.data.pageSize
    })
    wx.hideLoading()
    if (res.code == 404 || res.code == 700) {
      let newData = {
        loadingMoreHidden: false
      }
      if (!append) {
        newData.goods = []
      }
      this.setData(newData);
      return
    }
    let goods = [];
    if (append) {
      goods = this.data.goods
    }
    for (var i = 0; i < res.data.result.length; i++) {
      const item = res.data.result[i]
      const hidden_goods_index = wx.getStorageSync('hidden_goods_index')
      if (hidden_goods_index.indexOf(item.id) != -1) {
        continue
      }
      goods.push(item);
    }
    this.setData({
      loadingMoreHidden: true,
      goods: goods,
    });
  },

  onShareAppMessage: function () {
    return {
      title: '"' + wx.getStorageSync('mallName') + '" ' + wx.getStorageSync('share_profile'),
      // path: '/pages/index/index?inviter_id=' + wx.getStorageSync('uid')
    }
  },
  onShareTimeline() {
    return {
      title: '"' + wx.getStorageSync('mallName') + '" ' + wx.getStorageSync('share_profile'),
      // query: 'inviter_id=' + wx.getStorageSync('uid'),
      // imageUrl: wx.getStorageSync('share_pic')
    }
  },

  onReachBottom: function () {
    this.setData({
      curPage: this.data.curPage + 1
    });
    this.getGoodsList(0, true)
  },
  onPullDownRefresh: function () {
    this.setData({
      curPage: 1
    });
    this.getGoodsList(0)
    wx.stopPullDownRefresh()
  }
})